package com.gxgeek.javabasic.dynamicproxy.jdk;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * Created by Administrator on 2017/7/9.
 */
public class Main {

    public static void main(String[] args) {
//        UserService userService = new UserServiceImpl();
//        InvocationHandler invocationHandler = new MyInvocationHandler(userService);
//        UserService userServiceProxy = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
//        userService.getClass().getInterfaces(), invocationHandler);
//        System.out.println(userServiceProxy.getName(1));
//        System.out.println(userServiceProxy.getAge(1));
        proxyCalssByJDK();

//        createProxyClassFile();
    }
    private static void proxyCalssByJDK(){
        UserService userServiceProxy = (UserService) Proxy.newProxyInstance(UserService.class.getClassLoader(),
                                        new Class<?>[]{UserService.class},
//                                        UserService.class.getInterfaces(),
                                        new MyInvocationHandler(new UserServiceImpl()));
        userServiceProxy.getName(1);
        userServiceProxy.getAge(1);
    }



    private static void createProxyClassFile() {
        String name = "ProxySubject";
        byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { UserService.class } );
        try
        {
            FileOutputStream out = new FileOutputStream( "D:\\works\\javastudy\\src\\main\\java\\com\\gx\\dynamicproxy\\jdk\\"+name + ".class" );
            out.write( data );
            out.close();
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }

    }

}
